package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    Configuration configuration;
    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    @Qualifier("minIOFileStorageService")
    FileStorageService fileStorageService;

    @Value("${file.minio.prefix}")
    String prefix;

    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            Template template = configuration.getTemplate("article.ftl");
            Map<String,Object> map = new HashMap<>();
            map.put("article",apArticle);
            map.put("content", JSON.parseArray(content,Map.class));
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            map.put("authorApUserId",apAuthor.getUserId());

            StringWriter stringWriter = new StringWriter();
            template.process(map,stringWriter);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
            log.info("生成静态页面成功  {}",path);

        } catch (Exception e) {
            log.error("生成静态页面失败 {}",e.getMessage());
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页面错误");
        }
    }
}
